/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.console.config.completer;

import org.jline.reader.Candidate;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;
import org.openislands.oi.console.config.bean.CommandGroupContext;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ParamsCompleter implements Completer {
    /***
     * File supplemented match prefix
     * See {@link #valueCandidate(ParsedLine, List)}
     */
    private static final Set<String> dirSet = new HashSet<>(Arrays.asList("./", "../", "/"));

    /***
     * Command method parameters candidates
     * Key see {@link #getNameKey(String, String)}
     * Load see {@link CommandGroupContext#initBean(Map)}
     */
    protected final Map<String, List<Candidate>> commandParamsCandidates;
    protected final Map<String, Set<String>> valueCache;

    public ParamsCompleter(Map<String, List<Candidate>> commandParamsCandidates) {
        this.commandParamsCandidates = commandParamsCandidates;
        this.valueCache = new HashMap<>();
        for (Map.Entry<String, List<Candidate>> entry : commandParamsCandidates.entrySet()) {
            valueCache.put(entry.getKey(),
                    entry.getValue().stream().map(Candidate::value).collect(Collectors.toSet()));
        }
    }

    @Override
    public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
        List<String> words = line.words();
        String readLine = reader.getBuffer().toString();
        if (words.size() < 2) {
            words = Arrays.stream(readLine.split(" ")).filter(s -> !s.isEmpty()).collect(Collectors.toList());
            if (words.size() < 2) return;
        }

        // command group and command match
        String nameKey = getNameKey(words.get(0), words.get(1));
        List<Candidate> candidateList = commandParamsCandidates.get(nameKey);
        if (Objects.nonNull(candidateList)) {

            // if, get candidates. else, matches all previous keys
            if (readLine.equals(line.line())) {
                // fill candidate
                valueCandidate(line, candidates);

                // prev key not param name
                String prevKey = words.get(words.size() - 2);
                if (!this.valueCache.get(nameKey).contains(prevKey)) {
                    // filter entered parameter
                    Set<String> filter = new HashSet<>(words);
                    Stream<Candidate> candidateStream = candidateList.stream()
                            .filter(candidate -> !filter.contains(candidate.value()));
                    candidates.addAll(candidateStream.collect(Collectors.toList()));
                }
            } else {
                candidates.addAll(words.stream().map(Candidate::new).collect(Collectors.toSet()));
            }
        }
    }

    /***
     * When the last work of the command is a parameter
     * Add candidates values that need to be supplemented
     * @param line          The parsed command line
     * @param candidates    The {@link List} of candidates to populate
     */
    protected void valueCandidate(ParsedLine line, List<Candidate> candidates) {
        String word = line.word();
        // file match candidate
        for (String dirWith : dirSet) {
            if (word.startsWith(dirWith)) {
                int endIndex = word.lastIndexOf("/") + 1;
                String directoryPath = word.substring(0, endIndex);
                File directory = new File(directoryPath);
                if (directory.exists()) {
                    File[] listFiles = directory.listFiles();
                    if (Objects.nonNull(listFiles)) {
                        for (File childFile : listFiles) {
                            String value = childFile.getPath().replace("\\", "/");
                            if (value.startsWith(word)) {
                                candidates.add(getCandidate(value, value, "file list", childFile.isFile()));
                            }
                        }
                    }
                }
                break;
            }
        }
    }

    public static String getNameKey(String groupName, String commandName) {
        return groupName + " " + commandName;
    }

    public static Candidate getCandidate(String value, String view, String group, boolean complete) {
        value = !complete && !value.endsWith("/") ? value + "/" : value;
        return new Candidate(value, view, group, null, null, null, complete);
    }
}
